# -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect
#from django.utils.translation import ugettext as _
from ragendja.template import render_to_response
from moral.forms import ChangeMoralForm, ChangeBanfeiForm
from moral.models import *
#from PyFetion import *
from django.contrib import auth
from django.contrib.auth.models import User, Group
from django.contrib.auth.decorators import login_required, permission_required
import datetime
import time
from google.appengine.api.labs import taskqueue 


_BASE_PRI_MORAL = 60.0
_BASE_PUB_MORAL = 60.0
_DEFAULT_PWD = 'sha1$48236$ed3c57b1cfcc3a18ab52715daa933e673860e82d'

COUNTER = 0
STUDENTS = Student.get_students()
BANFEILOG = Banfei_Log.all()
BANFEI = 0

def register(request):
    pass
#    return render_to_response()

def _cntime():
    return datetime.datetime.utcnow() + datetime.timedelta(hours= +8)

def wakeup(request):
    page_title = "Wake up"
    now = datetime.datetime.now()
    cnnow = _cntime()
    global COUNTER    
    COUNTER += 1    
    cc = COUNTER
    taskqueue.add(url='/wakeup/')
#    import time
#    time.sleep(10.0)
    return render_to_response(request, "moral/showmessage.html", locals())

def load_global():
    global BANFEILOG
    BANFEILOG = Banfei_Log.all()

    global BANFEI
    BANFEI = 0
    for bflog in BANFEILOG:
        BANFEI += bflog.amount
            
    global STUDENTS
    STUDENTS = Student.get_students()
    
def update_cache(request):
    load_global()
    return render_to_response(request, "moral/showmessage.html", locals())
    
def login(request):
    username = ''
    password = ''
    msg = '请先登录！'
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = auth.authenticate(username=username, password=password)
        if user is not None and user.is_active:
            # Correct password, and the user is marked "active"
            auth.login(request, user)
            # Redirect to a success page.
            return HttpResponseRedirect("/")
        elif user is not None and user.is_active is not True:
            msg = '用户被锁定，请联系班长!'            
        else:
            msg = '用户名密码错误！'
    return render_to_response(request, "moral/login.html", {'username':username, 'msg':msg})


def get_student_by_user(user):
    students = Student.gql("where user=:1", user)
    student = students.get()
    return student

def get_student_by_user_key(key):
    user = db.get(key)
    students = Student.gql("where user =:1", user)
    student = students.get()
    return student

weekday_dict = {
    1:"一",
    2:"二",
    3:"三",
    4:"四",
    5:"五",
    6:"六",
    7:"日",
}
            
@login_required
def index(request):
    page_title = "班级主页"
    global BANFEI
    banfei = BANFEI
    today = _cntime().date()
    weekday = "星期" + weekday_dict[today.isoweekday()]
    return render_to_response(request, "moral/index.html", locals())


#@login_required
#def send_sms(request):
#    page_title="Fetion测试"
#    msg="发送成功"
#    phone = PyFetion("13805046110","fetion123456","HTTP")
#    phone.login()
#    phone.send_sms("Hello, 这是从GAE发来的！"+str(counter),long=True)
#    return render_to_response(request, "moral/showmessage.html", locals())

@login_required
def userinfo(request):
    page_title = "个人信息"
    student = get_student_by_user(request.user)
    reflash_moral(student.id)
    return render_to_response(request, "moral/userinfo.html", {'stu':student, "page_title":page_title})

@login_required
def show_user(request, stu_key): 
    stu = Student.get((str(stu_key)))
    page_title = stu.user.first_name + u"的信息"
    return render_to_response(request, "moral/show_user.html", locals())

@login_required
def userlist(request):
    page_title = "同学列表"
    global STUDENTS
    students = STUDENTS
#    query=Student.all()
#    query.order('sitenum')
#    students = query.fetch(100)
    return render_to_response(request, "moral/userlist.html", {'Students':students, "page_title":page_title})


@permission_required('moral.can_change_moral_pri')
def change_moral_pri(request, stu_key):
    page_title = "更改德育分（班级）"
    msg = ''
    student = Student.get((str(stu_key)))    
    if request.method == 'POST':
        form = ChangeMoralForm(request.POST)
        if form.is_valid():
            ml = form.save()
            ml.type = 1
            ml.addtime = _cntime()
            ml.student = student
            ml.operator = request.user
            ml.save()
#            msg=u"操作成功，因为  %s ，%s的班级德育分账户变化：%s"%(ml.reason,student.user.first_name,ml.mark)
            return HttpResponseRedirect("/moral_op_msg_%s.html" % ml.id)
    else:
        form = ChangeMoralForm(
        initial={'date':_cntime(), 'mark':'-'}
        )

    return render_to_response(request, "moral/change_moral.html", {'stu':student, 'form':form, 'msg':msg, "page_title":page_title})

@permission_required('moral.can_change_moral_pub')
def change_moral_pub(request, stu_key):
    page_title = "更改德育分（学校）"
    msg = ''
    student = Student.get((str(stu_key)))    
    if request.method == 'POST':
        form = ChangeMoralForm(request.POST)
        if form.is_valid():
            ml = form.save()
            ml.type = 2
            ml.student = student
            ml.operator = request.user
            ml.save()
#            msg=u"操作成功，因为  %s ，%s的班级德育分账户变化：%s"%(ml.reason,student.user.first_name,ml.mark)
            return HttpResponseRedirect("/moral_op_msg_%s.html" % ml.id)
    else:
        form = ChangeMoralForm(
        initial={'date':_cntime(), 'mark':'-'}
        )

    return render_to_response(request, "moral/change_moral.html", {'stu':student, 'form':form, 'msg':msg, "page_title":page_title})

def reflash_moral(student_key):
    student = Student.get(student_key)
    #班级账户更新
    query = Moral_Log.gql("where student =:1 and type=1", student)
    mls = query.fetch(1000)
    primark = 0
    for log in mls:
        primark += log.mark
    student.moral_pri_mark = _BASE_PRI_MORAL + primark
    #学校账户更新
    query = Moral_Log.gql("where student =:1 and type=2", student)
    mls = query.fetch(1000)
    pubmark = 0
    for log in mls:
        pubmark += log.mark
    student.moral_pub_mark = _BASE_PUB_MORAL + pubmark    
    student.save()
    global STUDENTS
    STUDENTS = Student.get_students()
    

@login_required
def moral_op_msg(request, log_key):
    #统计学生的德育分
    page_title = "更改德育分-操作结果"
    ml = Moral_Log.get(str(log_key)) 
    reflash_moral(ml.student.id)
    stu = ml.student
    type = 'pri'
    if ml.type == 2:
        type = 'pub'
    if ml.mark >= 0:
        opflag = u'加'
        opnum = ml.mark
    elif ml.mark < 0:
        opflag = u'扣'
        opnum = -ml.mark
    return render_to_response(request, "moral/moral_op_msg.html", locals())

@login_required
def moral_logs(request, type, stu_key):
    page_title = "德育分变化记录"
    typeid = 1
    typename = "班级"
    if type == 'pub':
        typeid = 2
        typename = "学校"
#    student=get_student_by_user(request.user)
    
    student = Student.get(str(stu_key))
    query = Moral_Log.gql("where student =:1 and type=:2 order by date desc", student, typeid)
    mls = query.fetch(1000)    
    return render_to_response(request, "moral/moral_log.html", locals())

@permission_required('moral.can_reset_userpwd')
def reset_userpwd(request, student_key):
    page_title = "确认重设密码"
    student = Student.get(str(student_key))
    stuuser = student.user
    if request.method == 'POST':
        if stuuser.is_superuser is not True:
            stuuser.password = _DEFAULT_PWD
            stuuser.save()
            page_title = "密码重设成功"
            themsg = u'%s的密码重设为"1"！' % student.user.first_name
        else:
            themsg = u"不能重设超级管理员的密码！"
            page_title = "密码重设失败！"
        return render_to_response(request, "moral/showmessage.html", locals())
        
    confirm_msg = u'''确认重设%s的密码为“1”?''' % stuuser.first_name
    return render_to_response(request, "moral/confirm_form.html", locals())
    
@login_required
def banfei_log(request):
    page_title = "班费收支记录"
#    banfei=Banfei_Log.get_banfei()
#    bls=Banfei_Log.all()
    global BANFEILOG
    bls = BANFEILOG
    global BANFEI
    banfei = BANFEI
    return render_to_response(request, "moral/banfei_log.html", locals())
   

@permission_required('moral.can_manage_banfei')   
def change_banfei(request):
    page_title = "修改班费"
#    banfei=Banfei_Log.get_banfei()
    global BANFEI
    banfei = BANFEI
    if request.method == 'POST':
        form = ChangeBanfeiForm(request.POST)        
        if form.is_valid():
            bfl = form.save()
            bfl.op = request.user  
            bfl.save()  
            change_msg = "修改成功!"
            return HttpResponseRedirect("/change_banfei.html")
    else:
        form = ChangeBanfeiForm(
        initial={'date':datetime.date.today(), 'amount':'-'}
        )
    return render_to_response(request, "moral/change_banfei.html", locals())

@permission_required('moral.can_roll_call')
def roll_call(request):
    page_title = "点名"
    global STUDENTS
    Students = STUDENTS
#    query=Student.all()
#    query.order('sitenum')
#    Students = query.fetch(100)
    errors = []
    if request.method == 'POST':
        if not request.POST.get('date', ''):
            errors.append(u'请输入日期')
        if not request.POST.get('lesson', ''):
            errors.append(u'请选择节次')
        datestr = request.POST['date']
        date = datetime.datetime.strptime(datestr, "%Y-%m-%d").date() 
        order = int(request.POST['order'])
        att = Attendance()
        att.date = date
        att.order = order
        statu_normal=""
        statu_late=""
        statu_truant=""
        statu_leaveearly=""
        statu_leaving=""
        att_dict={
                  1:statu_normal,
                  2:statu_late,
                  3:statu_truant,
                  4:statu_leaveearly,
                  5:statu_leaving,
                  }
        for stu in Students: 
            statu = int(request.POST["roll_call_%s" % (stu.sitenum)])
            att_dict[statu]=att_dict[statu]+str(stu.id)+","
        att.statu_normal=att_dict[1]
        att.statu_late=att_dict[2]
        att.statu_truant=att_dict[3]
        att.statu_leaveearly=att_dict[4]
        att.statu_leaving=att_dict[5]
        att.save()
    return render_to_response(request, "moral/roll_call.html", locals())

def zhiri(request):
    pass

load_global()
#@permission_required('moral.can_upload_users')
#def upload_users(request):
#    page_title = "上传学生文件"
#    msg = ""
#    file_obj = request.FILES.get('file', None)
#    if request.method == 'POST':
#        if file_obj:
#            import csv
#            import StringIO
#            buf = StringIO.StringIO(file_obj.read())
#            try:
#                reader = csv.reader(buf)
#            except:
#                return render_to_response('address/showmessage.html',
#                    {'msg':'你需要上传一个csv格式的文件！'})
#            for row in reader:
#                obj = User(username=row[0], password=_DEFAULT_PWD,
#                    first_name=smart_unicode(row[1]))
#                obj.save()
#            return HttpResponseRedirect('/')
#        else:
#            msg = "你需要上传一个文件！"
#    return render_to_response(request, 'moral/upload_user.html', {'msg':msg, "page_title":page_title})
#
#@permission_required('moral.can_upload_users')
#def init_student(request):
#    users=User.all()
#    for tuser in users:
#        stu=Student(user=tuser,sitenum=int(tuser.username),moral_pri_mark=_BASE_PRI_MORAL,moral_pub_mark=_BASE_PUB_MORAL)
#        stu.save()
#    return render_to_response(request, 'moral/upload_user.html', {'msg':"学生已初始化"})
#    
def initdb(request):
    
    g1 = Position(title=u"无")
    g1.save()
    
    g2 = Position(title=u"班长")
    g2.save()
    
    g3 = Position(title=u"班主任")
    g3.save()
    
    user1 = User.objects.create_user(username='61', email='aa@bb.com', password='1')
    user1.first_name = u'学生'
    user1.is_active = True
    user1.save()
    

    stu1 = Student(user=user1, sitenum=61, moral_pri_mark=60.0, moral_pub_mark=60.0, position=g1, phonenum="1381111111")
    stu1.save()  
    
    user2 = User.objects.create_user(username='62', email='bb@bb.com', password='1')
    user2.first_name = u'班长学生'
    user2.is_active = True
    user2.save()
    
    stu2 = Student(user=user2, sitenum=62,
    moral_pri_mark=60.0, moral_pub_mark=60.0, position=g2, phonenum="1381111111")
    stu2.save()
    
    user3 = User.objects.create_user(username='63', email='cc@bb.com', password='1')
    user3.first_name = u'班主任'
    user3.is_active = True
    user3.is_staff = True
    user3.is_superuser = True
    user3.save()
    
    stu3 = Student(user=user3, sitenum=63,
    moral_pri_mark=60.0, moral_pub_mark=60.0, position=g3, phonenum="1381111111")
    stu3.save()
    
    return render_to_response(request, "moral/login.html", {'msg':"数据库已初始化"})
